﻿
#if UNITY_EDITOR

using UnityEngine;
using XYRendering.Vegetation;


namespace nTools.PrefabPainter
{
    [ExecuteAlways]
    [DisallowMultipleComponent]
    public class PrefabPainterDataBakePreviewer : MonoBehaviour
    {

        public VGInstancingDataBakeSetting bakeSetting;
        public VGInstancingDataBakePreviewSetting prevSetting;

        Renderer _renderer;
        MeshDivisionUtil _md;
        bool _IsDirty = false;
        
        public void SetDirty()
        {
            _IsDirty = true;
        }

        private void OnEnable()
        {
            _renderer = GetComponent<Renderer>();
        }
        
        
        private void OnDrawGizmos()
        {
            if (!_renderer || prevSetting == null || bakeSetting == null)
                return;

            if (_IsDirty)
            {
                if (_md == null)
                    _md = new MeshDivisionUtil();
                
                _md.Divide(gameObject, bakeSetting.division, bakeSetting.autoHeightAdaption);
                _IsDirty = false;
            }
            
            Color backupColor = Gizmos.color;
            Vector3 offset = new Vector3(0, bakeSetting.blockHeightOffset, 0);
            
            if (prevSetting.showBounds)
            {
                Gizmos.color = prevSetting.boundsColor;
                Gizmos.DrawWireCube(_renderer.bounds.center, _renderer.bounds.size);
            }

            if (prevSetting.showBlock)
            {
                Gizmos.color = prevSetting.blockColor;
                for (int i = 0; i < _md.numBounds; i++)
                {
                    var b = _md[i].Value;
                    Gizmos.DrawWireSphere(b.center + offset,  Mathf.Min(Mathf.Min(b.extents.x, b.extents.y), b.extents.z));
                   // Gizmos.DrawWireCube(b.center + offset, b.size);
                }
            }

            if (prevSetting.showBlockIndex)
            {
                var lableStyle = new GUIStyle();
                lableStyle.normal.textColor = prevSetting.indexColor;
                lableStyle.fontSize = 16;
                
                for (int i = 0; i < _md.numBounds; i++)
                {
                    var ib = _md[i];
                    
                    UnityEditor.Handles.Label(ib.Value.center + offset, string.Format("({0}, {1})", ib.Key.x, ib.Key.y), lableStyle);
                }
            }
            
            Gizmos.color = backupColor;
            
        }

    }
}

#endif  